package xin.nick.system.manager;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import xin.nick.system.config.ApplicationSystemProperties;
import xin.nick.system.entity.SystemUser;
import xin.nick.system.mapper.SystemUserMapper;

import java.util.List;
import java.util.Objects;

/**
 * @author Nick
 * @since 2023/1/3
 */
@Component
@RequiredArgsConstructor
public class SystemUserManager {

    private final SystemUserMapper systemUserMapper;
    private final ApplicationSystemProperties systemProperties;


    /**
     * 检查用户是否存在
     *
     * @param userId userId
     */
    public void checkUser(Long userId) {
        Assert.notNull(userId, "[id]不可为空");
        SystemUser systemUser = systemUserMapper.selectById(userId);
        Assert.notNull(systemUser, "系统用户不存在");
    }

    /**
     * 根据条件查询list的第一个, 和 getOne 平替
     *
     * @param queryWrapper
     * @return
     */
    public SystemUser getListFirst(Wrapper<SystemUser> queryWrapper) {
        List<SystemUser> systemUserList = systemUserMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(systemUserList)) {
            return null;
        }
        return systemUserList.get(0);
    }

    /**
     * 是否为rootId
     *
     * @param userId
     * @return
     */
    public boolean isRoot(Long userId) {
        return Objects.equals(systemProperties.getRootId(), userId);
    }

    /**
     * 检测是否有重复的账号
     *
     * @param username
     * @param userId
     */
    public void checkUsernameRepeat(String username, Long userId) {

        if (CharSequenceUtil.isBlank(username)) {
            return;
        }

        boolean hasUsername = StringUtils.hasLength(username);
        Assert.isTrue(hasUsername, "username 为空");

        SystemUser systemUser = getUserByUsername(username);
        if (Objects.nonNull(systemUser)) {
            // 如果是更新用户的话,再判断一下 userId, 存在用户且不是当前修改的用户,则抛出错误
            boolean isSelf = Objects.equals(systemUser.getUserId(), userId);
            Assert.isTrue(isSelf, "已存在相同的 username");
        }

    }


    /**
     * 根据用户名称获取系统用户信息
     * @param username
     * @return
     */
    public SystemUser getUserByUsername(String username) {
        if (CharSequenceUtil.isBlank(username)) {
            return null;
        }
        return systemUserMapper.selectOne(Wrappers.<SystemUser>lambdaQuery().eq(SystemUser::getUsername, username).last(" limit 1 "));
    }
}
